<template>
  <page-header-wrapper>
    <a-card>
      <JeepaySearchForm v-if="$access('ENT_UR_ROLE_SEARCH')" :searchConditionNum="6" :searchFunc="searchFunc" :resetFunc="() => { data.searchData= {} }">
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="data.searchData['sysType']" placeholder="所属系统">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="PLATFORM">运营平台</a-select-option>
            <a-select-option v-if="$hasAgentEnt()" value="AGENT">代理商</a-select-option>
            <a-select-option value="MCH">商户</a-select-option>
          </a-select>
        </a-form-item>
        <jeepay-text-up v-model:value="data.searchData['belongInfoId']" :placeholder="hasAgent" />
        <jeepay-text-up v-model:value="data.searchData['sysUserId']" :placeholder="'用户ID'" />
        <jeepay-text-up v-model:value="data.searchData['realname']" :placeholder="'用户姓名'" />
        <jeepay-text-up v-model:value="data.searchData['telphone']" :placeholder="'用户手机号'" />
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="data.searchData['userType']" placeholder="操作员类型">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="1">超级管理员</a-select-option>
            <a-select-option value="2">普通操作员</a-select-option>
            <a-select-option value="3">商户扩展员</a-select-option>
            <a-select-option value="11">店长</a-select-option>
            <a-select-option value="12">店员</a-select-option>
          </a-select>
        </a-form-item>
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :init-data="true"
        :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns"
        :search-data="data.searchData"
        row-key="sysUserId"
        @btnLoadClose="data.btnLoading=false"
      >
        <template #topBtnSlot>
          <div>
            <a-button 
              v-if="$access('ENT_UR_USER_ADD')"
              type="primary"
              class="mg-b-30"
              @click="addFunc"
            >
              <plus-outlined />
              新建
            </a-button>
          </div>
        </template>
        <template #bodyCell="{column,record}">
          <template v-if="column.key === 'avatar'">
            <a-avatar size="default" :src="record.avatarUrl" />
          </template>
          <template v-if="column.key === 'realname'">
            {{ record.realname }}
            <a-tag v-if="record.initUser" :key="record.initUser" color="green">
              初始
            </a-tag>
          </template>
          <template v-if="column.key === 'state'">
            <JeepayTableColState :state="record.state" :show-switch-type="$access('ENT_UR_USER_EDIT')" :on-change="(state) => { return updateState(record.sysUserId, state)}" />
          </template>
          <template v-if="column.key === 'inviteCode'">
            <span v-if="(record.userType == 1 || record.userType == 3) && record.inviteCode">
              <a-button v-clipboard:copy="record.inviteCode" v-clipboard:success="() => $infoBox.message.success('邀请码已复制')" type="link" size="small">{{ record.inviteCode }}</a-button>
              <info-circle-outlined style="cursor: pointer;" @click="showQrImgFunc(record)" />
            </span>
            <span v-else />
          </template>

          <template v-if="column.key === 'sex'">
            <span v-if="record.sex == 1">男</span>
            <span v-else-if="record.sex == 2">女</span>
            <span v-else>未知</span>
          </template>
          
          <template v-if="column.key === 'belongInfoId'">
            <span v-if="record.belongInfoId != 0">{{ record.belongInfoId }}</span>
            <span v-else />
          </template>

          <template v-if="column.key === 'userType'">
            <span v-if="record.userType == 1">超级管理员</span>
            <span v-else-if="record.userType == 2">普通操作员</span>
            <span v-else-if="record.userType == 3">商户拓展员</span>
            <span v-else-if="record.userType == 11">店长</span>
            <span v-else-if="record.userType == 12">店员</span>
            <span v-else>其他</span>
          </template>

          <template v-if="column.key === 'op'">
            <!-- 操作列插槽 -->
            <JeepayTableColumns>
              <a-button v-if="$access('ENT_UR_USER_VIEW')" type="link" @click="detailFunc(record.sysUserId)">详情</a-button>
              <a-button v-if="$access('ENT_UR_USER_UPD_ROLE') && record.userType == '2'" type="link" @click="roleDistFun(record.sysUserId)">变更角色</a-button>
              <a-button v-if="$access('ENT_UR_USER_EDIT')" type="link" @click="editFunc(record.sysUserId)">修改</a-button>
              <a-button v-if="$access('ENT_UR_USER_MFA_DELETE') && (userStore.userInfo['userType'] == '1' && record.mfaBindState == '1')" style="color: red;" type="link" @click="mfaRelieve(record.sysUserId)">MFA解绑</a-button>
              <a-button v-if="$access('ENT_UR_USER_EDIT') && (record.userType == '11' || record.userType == '12')" type="link" @click="bindStoreFunc(record.sysUserId, record.userType, record.belongInfoId)">门店绑定</a-button>
              <a-button v-if="$access('ENT_UR_USER_LOGIN_LIMIT_DELETE')" style="color: red;" type="link" @click="deleteLoginLimit(record.sysUserId)">解除登录限制</a-button>
              <a-button v-if="$access('ENT_UR_USER_DELETE')" type="link" style="color: red;" @click="delFunc(record.sysUserId)">删除</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>
    </a-card>

    <a-modal v-model:visible="data.codeVisible" title="邀请码" :footer="null" :width="600" @ok="() => data.codeVisible = false">
      <div v-if="!data.inviteCode">
        <span>无邀请码</span>
        <a-button type="link" @click="setInviteCodeFunc(data.sysUserId)">点此修复</a-button>
      </div>
      <div v-else>
        <div>
          <span>邀请码：{{ data.inviteCode }}</span>
          <a-button v-clipboard:copy="data.inviteCode" v-clipboard:success="() => $infoBox.message.success('邀请码已复制')" type="link">复制</a-button>
        </div>

        <div>
          <div>
            <span>商户注册链接：{{ data.inviteCodeUrl }}</span>
            <a-button v-clipboard:copy="data.inviteCodeUrl" v-clipboard:success="() => $infoBox.message.success('复制成功')" type="link">复制</a-button>
          </div>
          <div>
            <span>商户注册二维码：</span>
            <div style="padding: 20px 0 20px 50px;"><QrcodeVue :value="data.inviteCodeUrl" :size="200" /></div>
          </div>
        </div>

        <div v-if="data.sysType == 'PLATFORM' || data.sysType == 'AGENT'">
          <div>
            <span>代理商注册链接：{{ data.agentInviteCodeUrl }}</span>
            <a-button v-clipboard:copy="data.agentInviteCodeUrl" v-clipboard:success="() => $infoBox.message.success('复制成功')" type="link">复制</a-button>
          </div>
          <div>
            <span>代理商注册二维码：</span>
            <div style="padding: 20px 0 20px 50px;"><QrcodeVue :value="data.agentInviteCodeUrl" :size="200" /></div>
          </div>
        </div>
      </div>
    </a-modal>

    <!-- 新增 / 修改 页面组件  -->
    <InfoAddOrEdit ref="infoAddOrEdit" :callback-func="searchFunc" />

    <!-- 分配角色 页面组件  -->
    <RoleDist ref="roleDist" />

    <!-- 详情页面组件  -->
    <InfoDetail ref="infoDetail" :callback-func="searchFunc" />
    <!-- 绑定门店 -->
    <InfoBindStore ref="infoBindStore" :callbackFunc="searchFunc" />
  </page-header-wrapper>
</template>
<script setup lang="ts">
import { API_URL_SYS_USER_LIST, req, reqLoad, $deleteLoginLimit } from '@/api/manage'
import { useUserStore } from '@/store/modules/user'
import InfoAddOrEdit from './AddOrEdit.vue'
import RoleDist from './RoleDist.vue'
import InfoDetail from './Detail.vue'
import InfoBindStore from './BindStore.vue'
import QrcodeVue from 'qrcode.vue'
import { reactive,ref,getCurrentInstance} from 'vue'

const userStore = useUserStore()
const { $infoBox, $access, $hasAgentEnt } = getCurrentInstance()!.appContext.config.globalProperties

let hasAgent = ref($hasAgentEnt() ? '所属代理商/商户' : '商户号')

const tableColumns = reactive([
  {key:'avatar',title: '头像', },
  {key:'realname', title: '姓名',   dataIndex: 'realname' },
  {key:'sysUserId', title: '用户ID', dataIndex: 'sysUserId', },
  {key:'sex', title: '性别', dataIndex: 'sex',  },
  {key:'userNo', title: '编号', dataIndex: 'userNo',   },
  {key:'telphone', title: '手机号', dataIndex: 'telphone',  },
  {key:'belongInfoId' ,title: hasAgent.value, dataIndex: 'belongInfoId' },
  {key:'userType' ,title: '操作员类型', dataIndex: 'userType' },
  {key:'teamName' ,title: '团队', dataIndex: 'teamName' },
  {key:'inviteCode' ,title: '邀请码', dataIndex: 'inviteCode', },
  {key:'state', title: '状态', align: 'center' , },
  {key:'createdAt', title: '创建时间', dataIndex: 'createdAt', },
  {key: 'op',title: '操作',   fixed: 'right',align: 'center' } 
])

    const infoTable = ref()
    const infoDetail = ref()
    const infoAddOrEdit =ref()
    const roleDist = ref()
    const infoBindStore = ref()

    let data : any = reactive ({
      tableColumns: tableColumns,
      searchData: { 'sysType': 'PLATFORM' } as any,
      btnLoading: false
    })

    // 请求table接口数据
    function reqTableDataFunc(params){
      return req.list(API_URL_SYS_USER_LIST, params)
    }

    function searchFunc() { // 点击【查询】按钮点击事件
      data.btnLoading = true // 打开查询按钮的loading
      infoTable.value.refTable(true)
    }

    function addFunc () { // 业务通用【新增】 函数
      infoAddOrEdit.value.show()
    }

    function editFunc (recordId) { // 业务通用【修改】 函数
      infoAddOrEdit.value.show(recordId)
    }
    function detailFunc (recordId: any) { // 商户详情页
      infoDetail.value.show(recordId)
    }
    function bindStoreFunc(recordId, userType, belongInfoId) {  // 绑定门店
      infoBindStore.value.show(recordId, userType, belongInfoId)
    }
    function setInviteCodeFunc (recordId: any) { // 修复邀请码
      return req.updateById(API_URL_SYS_USER_LIST, recordId, { setInviteCode: true }).then(res => {
        $infoBox.message.success('修复成功')
        console.log(res)
        showQrImgFunc(res)
        infoTable.value.refTable(false)
      })
    }

    function delFunc(recordId) { // 业务通用【删除】 函数
      $infoBox.confirmDanger('确认删除？', '', () => {
        return req.delById(API_URL_SYS_USER_LIST, recordId).then(res => {
          $infoBox.message.success('删除成功！')
          infoTable.value.refTable(false)
        })
      })
    }

    function mfaRelieve(recordId) { // MFA解绑
      $infoBox.confirmDanger('确认解绑吗？', '', () => {
        return req.updateById(API_URL_SYS_USER_LIST, 'mfaRelieve', {recordId: recordId}).then(res => {
          $infoBox.message.success('解绑成功！')
          infoTable.value.refTable(false)
        })
      })
    }

    function deleteLoginLimit(recordId) { // 解除登录限制
      $infoBox.confirmDanger('确认解除吗？', '', () => {
        return $deleteLoginLimit(recordId).then(res => {
          $infoBox.message.success('解除成功！')
          infoTable.value.refTable(false)
        })
      })
    }

    function roleDistFun(recordId) { // 【分配权限】 按钮点击事件
      roleDist.value.show(recordId)
    }

    function updateState (recordId, state) { // 【更新状态】
      const title = state === 1 ? '确认[启用]该用户？' : '确认[停用]该用户？'
      const content = state === 1 ? '启用后用户可进行登陆等一系列操作' : '停用后该用户将立即退出系统并不可再次登陆'

      return new Promise<void>((resolve, reject) => {
        $infoBox.confirmDanger(title, content, () => {
          return reqLoad.updateById(API_URL_SYS_USER_LIST, recordId, { state: state }).then(res => {
            searchFunc()
            resolve()
          }).catch(err => reject(err))
        },
          () => {
          reject(new Error())
        })
      })
    }

    // 显示二维码图片
    function showQrImgFunc(record){
      data.codeVisible = true
      data.inviteCodeUrl = record.inviteCodeUrl
      data.inviteCode = record.inviteCode
      data.sysUserId = record.sysUserId
      data.agentInviteCodeUrl = record.agentInviteCodeUrl
      data.sysType = record.sysType
    }

    function onCopySuccess () {
      $infoBox.message.success('复制成功')
    }

</script>
